// src/pages/TopicDetail.js - 话题详情页面

import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Typography, Card, List, Avatar, Button, Space, Tag, Statistic,
  Modal, Form, Input, Select, Row, Col, message, Empty, Divider,
  Badge, Tooltip, Spin, Comment, Tabs, Alert, Dropdown, Menu
} from 'antd';
import {
  ArrowLeftOutlined, UserOutlined, CommentOutlined, EyeOutlined,
  MessageOutlined, TeamOutlined, StarOutlined, ClockCircleOutlined,
  PlusOutlined, LikeOutlined, EditOutlined, DeleteOutlined,
  SendOutlined, PushpinOutlined, SettingOutlined, CrownOutlined
} from '@ant-design/icons';
import { topics } from '../services';
import TopicPostDetail from '../components/TopicPostDetail';
import TopicAdminPanel from '../components/TopicAdminPanel';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const TopicDetail = () => {
  const { topicId } = useParams();
  const navigate = useNavigate();
  const [topic, setTopic] = useState(null);
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isPostModalVisible, setIsPostModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('posts');
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const [currentUser, setCurrentUser] = useState(null);
  const [isJoined, setIsJoined] = useState(false);
  const [selectedPost, setSelectedPost] = useState(null);
  const [isPostDetailVisible, setIsPostDetailVisible] = useState(false);
  const [isAdminPanelVisible, setIsAdminPanelVisible] = useState(false);
  const [deleteConfirmVisible, setDeleteConfirmVisible] = useState(false);
  const [deleteType, setDeleteType] = useState(''); // 'post' 或 'topic'
  const [deleteTargetId, setDeleteTargetId] = useState(null);
  const [likedPosts, setLikedPosts] = useState(new Set());

  const postTypes = [
    { value: 'chat', label: '讨论', color: '#1890ff', icon: CommentOutlined },
    { value: 'request', label: '资源求助', color: '#ff4d4f', icon: MessageOutlined },
    { value: 'resource', label: '资源分享', color: '#52c41a', icon: StarOutlined },
    { value: 'discussion', label: '闲聊', color: '#fa8c16', icon: TeamOutlined }
  ];

  useEffect(() => {
    loadTopicDetail();
    loadCurrentUser();
  }, [topicId]);

  const loadCurrentUser = () => {
    const user = JSON.parse(localStorage.getItem('starrypt_user') || 'null');
    console.log('当前用户:', user);
    setCurrentUser(user);

    // 如果没有用户数据，为测试目的创建一个临时用户
    if (!user) {
      const testUser = {
        username: 'test',
        email: 'test@pku.edu.cn',
        role: 'user'
      };
      localStorage.setItem('starrypt_user', JSON.stringify(testUser));
      console.log('创建测试用户:', testUser);
      setCurrentUser(testUser);
    }
  };

  const loadTopicDetail = async () => {
    try {
      setLoading(true);

      // 获取话题详情
      const topicResponse = await topics.getTopicDetail(topicId);
      if (topicResponse.success) {
        const topicData = topicResponse.data.topic;
        setTopic(topicData);

        // 根据后端返回的joined字段设置加入状态
        if (topicData.joined !== undefined) {
          console.log('话题加入状态:', topicData.joined);
          setIsJoined(topicData.joined);
        } else {
          // 如果后端没有返回joined字段，使用默认值
          setIsJoined(false);
        }
      }

      // 获取话题下的所有帖子
      const postsResponse = await topics.getTopicPosts(topicId);
      if (postsResponse.success) {
        const postsData = postsResponse.data.posts || [];
        setPosts(postsData);

        // 设置点赞状态
        const likedPostIds = new Set();
        postsData.forEach(post => {
          if (post.liked) {
            likedPostIds.add(post.postId);
          }
        });
        setLikedPosts(likedPostIds);
      }
    } catch (error) {
      console.error('加载话题详情失败:', error);
      message.error('加载话题详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleJoinTopic = async () => {
    try {
      const response = await topics.joinTopic(topicId);
      if (response.success) {
        messageApi.success('成功加入话题！');
        // 重新加载话题详情以获取最新的joined状态
        loadTopicDetail();
      } else {
        messageApi.error(response.message || '加入话题失败');
      }
    } catch (error) {
      console.error('加入话题失败:', error);
      messageApi.error('加入话题失败: ' + error.message);
    }
  };

  // 处理发布帖子
  const handleCreatePost = async (values) => {
    try {
      // 确保tags字段是字符串格式，因为后端期望字符串而不是数组
      const postData = {
        ...values,
        tags: values.tags ? (Array.isArray(values.tags) ? values.tags.join(',') : values.tags) : ''
      };

      const response = await topics.createTopicPost(topicId, postData);
      if (response.success) {
        messageApi.success('帖子发布成功！');
        setIsPostModalVisible(false);
        form.resetFields();
        loadTopicDetail(); // 重新加载数据
      } else {
        messageApi.error(response.message || '发布帖子失败');
      }
    } catch (error) {
      console.error('发布帖子失败:', error);
      messageApi.error('发布帖子失败: ' + error.message);
    }
  };

  // 处理帖子点击
  const handlePostClick = (post) => {
    setSelectedPost(post);
    setIsPostDetailVisible(true);
  };

  // 检查是否是管理员
  const isAdmin = () => {
    if (!currentUser || !topic) return false;
    return (
      currentUser.role === 'admin' ||
      currentUser.username === topic.creator ||
      (topic.moderators && topic.moderators.includes(currentUser.username))
    );
  };

  // 处理点赞帖子
  const handleLikePost = async (postId) => {
    try {
      const response = await topics.likeTopicPost(postId);
      if (response.success) {
        console.log('点赞操作响应:', response.data);

        // 立即更新UI状态
        setLikedPosts(prev => {
          const newSet = new Set(prev);
          if (newSet.has(postId)) {
            newSet.delete(postId);
          } else {
            newSet.add(postId);
          }
          return newSet;
        });

        // 更新帖子数据
        setPosts(prev => prev.map(post => {
          if (post.postId === postId) {
            const newLikes = response.data.likes !== undefined ? response.data.likes : post.likes;
            console.log(`帖子 ${postId} 点赞数更新: ${post.likes} -> ${newLikes}`);
            return {
              ...post,
              likes: newLikes,
              liked: !post.liked
            };
          }
          return post;
        }));

        message.success(likedPosts.has(postId) ? '取消点赞成功' : '点赞成功');
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      message.error('点赞操作失败');
    }
  };

  const handleDeletePost = async (postId) => {
    console.log('handleDeletePost 被调用，参数:', { topicId, postId });
    try {
      const response = await topics.deleteTopicPost(topicId, postId);
      console.log('删除帖子响应:', response);
      if (response.success) {
        messageApi.success('帖子删除成功');
        loadTopicDetail(); // 重新加载话题详情
        setIsPostDetailVisible(false);
        setSelectedPost(null);
        setDeleteConfirmVisible(false);
      } else {
        messageApi.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除帖子失败:', error);
      messageApi.error('删除帖子失败: ' + error.message);
    }
  };

  const handleDeleteTopic = async () => {
    console.log('handleDeleteTopic 被调用，topicId:', topicId);
    try {
      const response = await topics.deleteTopic(topicId);
      console.log('删除话题响应:', response);
      if (response.success) {
        messageApi.success('话题删除成功');
        navigate('/topics');
        setDeleteConfirmVisible(false);
      } else {
        messageApi.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除话题失败:', error);
      messageApi.error('删除话题失败: ' + error.message);
    }
  };

  const showDeleteConfirm = (type, targetId = null) => {
    setDeleteType(type);
    setDeleteTargetId(targetId);
    setDeleteConfirmVisible(true);
  };

  const handleConfirmDelete = async () => {
    if (deleteType === 'post') {
      await handleDeletePost(deleteTargetId);
    } else if (deleteType === 'topic') {
      await handleDeleteTopic();
    }
  };

  // 检查是否可以删除帖子（发帖者、话题创建者或管理员）
  const canDeletePost = (post) => {
    if (!currentUser || !currentUser.username) {
      console.log('canDeletePost: 无当前用户或用户名');
      return false;
    }

    console.log('canDeletePost 检查:', {
      currentUser: currentUser.username,
      postAuthor: post.author,
      topicCreator: topic?.creator,
      userRole: currentUser.role,
      topicModerators: topic?.moderators || []
    });

    // 检查是否是帖子作者
    const isAuthor = currentUser.username === post.author;
    // 检查是否是话题创建者
    const isTopicCreator = currentUser.username === topic?.creator;
    // 检查是否是系统管理员
    const isSystemAdmin = currentUser.role === 'admin';
    // 检查是否是话题管理员
    const isTopicModerator = topic?.moderators && topic.moderators.includes(currentUser.username);

    const result = isAuthor || isTopicCreator || isSystemAdmin || isTopicModerator;

    console.log('权限检查详情:', {
      isAuthor,
      isTopicCreator,
      isSystemAdmin,
      isTopicModerator,
      result
    });

    return result;
  };

  const formatTime = (timeString) => {
    const time = new Date(timeString);
    const now = new Date();
    const diffInSeconds = Math.floor((now - time) / 1000);

    if (diffInSeconds < 60) return '刚刚';
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`;
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`;
    if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)}天前`;

    return time.toLocaleDateString();
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" tip="加载话题详情..." />
      </div>
    );
  }

  if (!topic) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Empty description="话题不存在" />
        <Button type="primary" onClick={() => navigate('/topics')}>
          返回话题广场
        </Button>
      </div>
    );
  }

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 200px)' }}>
      {contextHolder}
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>
        {/* 话题信息头部 */}
        <Card style={{ marginBottom: 24 }}>
          <div style={{ marginBottom: 16 }}>
            <Button
              type="link"
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate('/topics')}
              style={{ padding: 0 }}
            >
              返回话题广场
            </Button>
          </div>

          <Row gutter={24} align="middle">
            <Col span={4}>
              <Avatar
                size={80}
                style={{ backgroundColor: '#722ed1' }}
                icon={<TeamOutlined />}
              />
            </Col>
            <Col span={20}>
              <Title level={2} style={{ margin: 0 }}>
                {topic.title || topic.name}
              </Title>
              <Paragraph style={{ marginTop: 8, marginBottom: 16 }}>
                {topic.description}
              </Paragraph>
              <Space>
                <Tag color="#722ed1">{topic.category}</Tag>
                {(typeof topic.tags === 'string' ? topic.tags.split(',') : (topic.tags || [])).map(tag => (
                  <Tag key={tag}>{tag.trim()}</Tag>
                ))}
                <Text type="secondary">创建于 {formatTime(topic.createTime)}</Text>
                <Statistic
                  title="成员数"
                  value={topic.memberCount || 0}
                  prefix={<UserOutlined />}
                />
                <Button
                  type={isJoined ? "default" : "primary"}
                  icon={<TeamOutlined />}
                  onClick={handleJoinTopic}
                  disabled={isJoined}
                  style={{
                    cursor: isJoined ? 'not-allowed' : 'pointer',
                    opacity: isJoined ? 0.6 : 1
                  }}
                >
                  {isJoined ? "已加入" : "加入话题"}
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 帖子列表 */}
        <Card>
          <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={4}>话题帖子</Title>
            <Space>
              {isAdmin() && (
                <Button
                  icon={<SettingOutlined />}
                  onClick={() => setIsAdminPanelVisible(true)}
                >
                  管理面板
                </Button>
              )}
              {(() => {
                const canDeleteTopic = currentUser?.username === topic?.creator || currentUser?.role === 'admin';
                console.log('删除话题权限检查:', {
                  currentUser: currentUser?.username,
                  topicCreator: topic?.creator,
                  userRole: currentUser?.role,
                  canDeleteTopic
                });
                return canDeleteTopic;
              })() && (
                  <Tooltip title="删除话题">
                    <Button
                      icon={<DeleteOutlined />}
                      danger
                      onClick={() => {
                        console.log('删除话题按钮被点击');
                        showDeleteConfirm('topic');
                      }}
                    >
                      删除话题
                    </Button>
                  </Tooltip>
                )}
              <Button type="primary" icon={<PlusOutlined />} onClick={() => setIsPostModalVisible(true)}>
                发布帖子
              </Button>
            </Space>
          </div>

          <Tabs activeKey={activeTab} onChange={setActiveTab}>
            <TabPane tab="全部帖子" key="posts">
              {posts.length > 0 ? (
                <List
                  dataSource={posts}
                  renderItem={(post) => {
                    const postType = postTypes.find(type => type.value === post.type) || postTypes[0];
                    const IconComponent = postType.icon;

                    return (
                      <List.Item
                        key={post.postId}
                        style={{
                          padding: '16px 0',
                          borderBottom: '1px solid #f0f0f0',
                          cursor: 'pointer',
                          transition: 'background-color 0.2s'
                        }}
                        className="hover:bg-gray-50"
                        onClick={() => handlePostClick(post)}
                        actions={[
                          <Button
                            type={likedPosts.has(post.postId) ? "primary" : "text"}
                            icon={<LikeOutlined />}
                            size="small"
                            className={likedPosts.has(post.postId) ? 'liked' : ''}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleLikePost(post.postId);
                            }}
                          >
                            {post.likes}
                          </Button>,
                          <Button type="text" icon={<CommentOutlined />} size="small">
                            {post.replies}
                          </Button>,
                          <Button type="text" icon={<EyeOutlined />} size="small">
                            {post.views}
                          </Button>,
                          <Tooltip title={`删除帖子 (${canDeletePost(post) ? '有权限' : '无权限'})`}>
                            <Button
                              type="text"
                              icon={<DeleteOutlined />}
                              size="small"
                              danger
                              disabled={!canDeletePost(post)}
                              onClick={(e) => {
                                e.stopPropagation();
                                console.log('删除帖子按钮被点击，帖子ID:', post.postId);
                                if (canDeletePost(post)) {
                                  console.log('用户有删除帖子权限');
                                  showDeleteConfirm('post', post.postId);
                                } else {
                                  console.log('用户没有删除帖子权限');
                                  messageApi.warning('您没有删除此帖子的权限');
                                }
                              }}
                            />
                          </Tooltip>
                        ].filter(Boolean)}
                      >
                        <List.Item.Meta
                          avatar={
                            <Avatar
                              style={{ backgroundColor: '#1890ff' }}
                              icon={<UserOutlined />}
                            />
                          }
                          title={
                            <Space>
                              {post.pinned && <Badge count="置顶" style={{ backgroundColor: '#722ed1' }} />}
                              <Tag color={postType.color} icon={<IconComponent />}>
                                {postType.label}
                              </Tag>
                              <Text strong>{post.title}</Text>
                              {post.bounty && <Tag color="gold">悬赏{post.bounty}星币</Tag>}
                            </Space>
                          }
                          description={
                            <div>
                              <Paragraph
                                ellipsis={{ rows: 2, expandable: true }}
                                style={{ margin: '8px 0' }}
                              >
                                {post.content}
                              </Paragraph>
                              <Space size="small">
                                <Text type="secondary">
                                  <UserOutlined /> {post.author}
                                </Text>
                                <Text type="secondary">
                                  <ClockCircleOutlined /> {formatTime(post.createTime)}
                                </Text>
                                {(typeof post.tags === 'string' ? post.tags.split(',') : (post.tags || [])).map(tag => (
                                  <Tag key={tag} size="small">{tag.trim()}</Tag>
                                ))}
                              </Space>
                            </div>
                          }
                        />
                      </List.Item>
                    );
                  }}
                />
              ) : (
                <Empty description="暂无帖子，快来发布第一个帖子吧！" />
              )}
            </TabPane>
            <TabPane tab="资源分享" key="resource">
              <List
                dataSource={posts.filter(post => post.type === 'resource')}
                renderItem={(post) => (
                  <List.Item
                    key={post.postId}
                    style={{ cursor: 'pointer' }}
                    onClick={() => handlePostClick(post)}
                  >
                    <List.Item.Meta
                      title={post.title}
                      description={post.content}
                    />
                  </List.Item>
                )}
              />
            </TabPane>
            <TabPane tab="求助帖" key="request">
              <List
                dataSource={posts.filter(post => post.type === 'request')}
                renderItem={(post) => (
                  <List.Item
                    key={post.postId}
                    style={{ cursor: 'pointer' }}
                    onClick={() => handlePostClick(post)}
                  >
                    <List.Item.Meta
                      title={post.title}
                      description={post.content}
                    />
                  </List.Item>
                )}
              />
            </TabPane>
          </Tabs>
        </Card>

        {/* 发布帖子Modal */}
        <Modal
          title="发布新帖子"
          open={isPostModalVisible}
          onCancel={() => {
            setIsPostModalVisible(false);
            form.resetFields();
          }}
          footer={null}
          width={700}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleCreatePost}
            style={{ marginTop: 16 }}
          >
            <Form.Item
              name="title"
              label="帖子标题"
              rules={[{ required: true, message: '请输入帖子标题' }]}
            >
              <Input placeholder="请输入帖子标题..." />
            </Form.Item>

            <Form.Item
              name="type"
              label="帖子类型"
              rules={[{ required: true, message: '请选择帖子类型' }]}
            >
              <Select placeholder="选择帖子类型">
                {postTypes.map(type => (
                  <Option key={type.value} value={type.value}>
                    <Space>
                      <span style={{ color: type.color }}>
                        <type.icon />
                      </span>
                      {type.label}
                    </Space>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="content"
              label="帖子内容"
              rules={[{ required: true, message: '请输入帖子内容' }]}
            >
              <TextArea
                placeholder="请输入帖子内容..."
                rows={6}
                showCount
                maxLength={1000}
              />
            </Form.Item>

            <Form.Item name="tags" label="标签">
              <Select
                mode="tags"
                placeholder="添加标签（回车确认）"
                maxCount={5}
              />
            </Form.Item>

            <Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}>
              {({ getFieldValue }) => {
                const type = getFieldValue('type');
                if (type === 'request') {
                  return (
                    <Form.Item name="bounty" label="悬赏星币">
                      <Input
                        type="number"
                        placeholder="悬赏星币数量（可选）"
                        min={0}
                        max={100}
                      />
                    </Form.Item>
                  );
                }
                return null;
              }}
            </Form.Item>

            <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
              <Space>
                <Button onClick={() => {
                  setIsPostModalVisible(false);
                  form.resetFields();
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit" icon={<SendOutlined />}>
                  发布帖子
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 帖子详情Modal */}
        <TopicPostDetail
          visible={isPostDetailVisible}
          onClose={() => {
            setIsPostDetailVisible(false);
            setSelectedPost(null);
          }}
          postId={selectedPost?.postId}
          topicId={topicId}
          topic={topic}
          currentUser={currentUser}
          onPostUpdate={loadTopicDetail}
          onPostDelete={handleDeletePost}
        />

        {/* 管理员面板Modal */}
        <TopicAdminPanel
          visible={isAdminPanelVisible}
          onClose={() => setIsAdminPanelVisible(false)}
          topic={topic}
          currentUser={currentUser}
          onTopicUpdate={loadTopicDetail}
          onTopicDelete={() => {
            setIsAdminPanelVisible(false);
            navigate('/topics');
          }}
        />

        {/* 删除确认对话框 */}
        <Modal
          title={deleteType === 'post' ? '确认删除帖子' : '确认删除话题'}
          open={deleteConfirmVisible}
          onCancel={() => {
            console.log('用户取消删除操作');
            setDeleteConfirmVisible(false);
            setDeleteType('');
            setDeleteTargetId(null);
          }}
          footer={[
            <Button
              key="cancel"
              onClick={() => {
                console.log('用户点击取消按钮');
                setDeleteConfirmVisible(false);
                setDeleteType('');
                setDeleteTargetId(null);
              }}
            >
              取消
            </Button>,
            <Button
              key="confirm"
              type="primary"
              danger
              onClick={() => {
                console.log('用户点击确认删除按钮');
                handleConfirmDelete();
              }}
            >
              确定删除
            </Button>,
          ]}
          centered
          maskClosable={false}
        >
          <p>
            {deleteType === 'post'
              ? '确定要删除这个帖子吗？删除后无法恢复。'
              : '确定要删除这个话题吗？删除后无法恢复，所有帖子和评论都会被删除。'
            }
          </p>
        </Modal>
      </div>
    </div>
  );
};

export default TopicDetail;